package itsm.isperp.module.controller.incident;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.domain.CountQuery;
import itsm.isperp.framework.web.request.DefaultCountQuery;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.incident.IcdCategory;
import itsm.isperp.module.entity.incident.IcdIncident;
import itsm.isperp.module.entity.serviceCatalog.SrcService;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.incident.IcdCategoryService;
import itsm.isperp.module.service.incident.IcdIncidentMajorService;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.module.service.incident.IcdMajorMemberService;
import itsm.isperp.module.service.project.ProjProjectService;
import itsm.isperp.module.service.serviceCatalog.SrcServiceService;
import itsm.isperp.module.service.slm.SlmServiceAgreementService;
import itsm.isperp.workflow.service.BpmProcessRunService;
import itsm.isperp.workflow.utils.BpmConst;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * 重要事件控制器
 * 
 * @author lizx
 * @since 1.0
 */
@Controller
@RequestMapping("incident/incident/major")
public class IcdIncidentMajorController {

	@Autowired
	protected IcdIncidentService icdIncidentService;
	@Autowired
	protected IcdIncidentMajorService icdIncidentMajorService;

	@Autowired
	protected AppDictService appDictService;

	@Autowired
	protected AppUserService appUserService;

	@Autowired
	protected ProjProjectService projProjectService;

	@Autowired
	protected BpmProcessRunService bpmProcessRunService;

	@Autowired
	protected SlmServiceAgreementService slmServiceAgreementService;

	@RequestMapping("analysis")
	public ModelAndView analysis(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("incident/incident/major/analysis");
		return mv;

	}

	/**
	 * 待判定界面
	 * 
	 * @param id
	 * @param req
	 * @return
	 */
	@RequestMapping("determineManage")
	public ModelAndView determineManage(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView(
				"incident/incident/major/determineManage");
		return mv;

	}

	@RequestMapping("listDetermineDetail")
	@ResponseBody
	public PageResponse<Map<String, Object>> listJudgeDetail(
			JqGridRequest request, HttpServletRequest req) {
		return this
				.getListDetail(createDetermineListCountQuery(), request, req);
	}

	/**
	 * 重要事件处理
	 * 
	 * @param id
	 * @param req
	 * @return
	 */
	@RequestMapping("manage")
	public ModelAndView manage(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("incident/incident/major/manage");
		return mv;

	}

	@RequestMapping("allMajorCount")
	@ResponseBody
	public long allMajorCount(String id, HttpServletRequest req) {

		CountQuery cq = new DefaultCountQuery("icd_incident");
		String processCondition = BpmConst
				.getQueryMyTaskSqlCondition("incidentProcess");
		String username = ContextHolder.getLoginUsername();

		cq.addCountFilter(
				"重要事件",
				true,
				" (status<>'已关闭' AND are_major=1 AND id IN (SELECT incident_id FROM icd_major_member WHERE username='"
						+ username
						+ "')) OR ( "
						+ "  priority_name =  '一级'  AND status IN ('二线受理','担当判定') AND "
						+ processCondition + ")");

		return cq.getTreeNodeCount("重要事件");
	}

	@RequestMapping("listDetail")
	@ResponseBody
	public PageResponse<Map<String, Object>> listDetail(JqGridRequest request,
			HttpServletRequest req) {
		return this.getListDetail(createListCountQuery(), request, req);
	}

	@RequestMapping("listAnalysis")
	@ResponseBody
	public PageResponse<Map<String, Object>> listAnalysis(
			JqGridRequest request, HttpServletRequest req) {
		return this.getListDetail(createAnalysisCountQuery(), request, req);
	}

	protected PageResponse<Map<String, Object>> getListDetail(CountQuery cq,
			JqGridRequest request, HttpServletRequest req) {
		String queryPath = req.getParameter("queryPath");

		if (cq != null) {
			request.setCountQuery(cq);
			request.setQueryPath(queryPath);

		}
		return this.icdIncidentService.findAllDetailByRequest(request).toPage();
	}

	protected CountQuery createAnalysisCountQuery() {
		CountQuery cq = new DefaultCountQuery("icd_incident");

		cq.addCountFilter("生产系统", true,
				" status<>'已关闭' AND  priority_name='二级' ");
		cq.addCountFilter("销售系统", true,
				"  status='已关闭' AND  priority_name='二级'");
		return cq;
	}

	@RequestMapping("listAllDetail")
	@ResponseBody
	public PageResponse<Map<String, Object>> listAllDetail(
			JqGridRequest request, HttpServletRequest req) {
		return this.getListDetail(createListCountQueryForAll(), request, req);
	}

	@RequestMapping("boardManage")
	public ModelAndView boardManage(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView(
				"incident/incident/major/boardManage");
		return mv;

	}

	protected CountQuery createListCountQueryForAll() {
		CountQuery cq = new DefaultCountQuery("icd_incident");

		cq.addCountFilter("处理中的重要事件", true, " status<>'已关闭' AND priority_name='一级'  ");
		cq.addCountFilter("已结束的重要事件", true, "  status='已关闭' AND priority_name='一级' ");
		return cq;
	}

	protected CountQuery createListCountQuery() {
		CountQuery cq = new DefaultCountQuery("icd_incident");
		String processCondition = BpmConst
				.getQueryMyTaskSqlCondition("incidentProcess");
		String username = ContextHolder.getLoginUsername();
		cq.addCountFilter("待判定的一级事件", true,
				"  priority_name =  '一级'  AND status IN ('二线受理','担当判定') AND "
						+ processCondition);

		cq.addCountFilter(
				"处理中的重要事件",
				true,
				" status<>'已关闭' AND priority_name='一级' AND id IN (SELECT incident_id FROM icd_major_member WHERE username='"
						+ username + "') ");

		cq.addCountFilter(
				"已结束的重要事件",
				true,
				"  status='已关闭' AND priority_name='一级'  AND id IN (SELECT incident_id FROM icd_major_member WHERE username='"
						+ username + "')");
		return cq;
	}

	protected CountQuery createDetermineListCountQuery() {
		CountQuery cq = new DefaultCountQuery("icd_incident");

		cq.addCountFilter("待二线判定", true,
				"   status<>'已关闭' AND status<>'工时审核'    AND  major_determine='待判定'");

		cq.addCountFilter("待担当判定", true, " status='担当判定'    ");
		cq.addCountFilter("已判定为重要的事件", true, " ( priority_name='一级' )");

		return cq;
	}

	@RequestMapping("edit")
	public ModelAndView edit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("incident/incident/major/edit");
		IcdIncident model = this.icdIncidentService.findOne(id);

		IUser u = ContextHolder.getLoginUser();

		IcdMajorMemberService icdMajorMemberService = ContextHolder
				.getSpringBean("icdMajorMemberService");
		boolean editable = icdMajorMemberService.isMember(id, u.getUsername());
		JdbcTemplate jdbcTemplate = ContextHolder
        .getSpringBean("jdbcTemplate");
		String readonly = req.getParameter("readonly");
		if ("1".equals(readonly)) {
			editable = false;
		}
		String sql="select * from icd_major_member where incident_id=?";
		List<Map<String,Object>> list=jdbcTemplate.queryForList(sql,id);
		if(list.size()==0)
		{
		  String sql1="SELECT b.name,b.fullname FROM v_app_user_role a inner join app_user b on a.app_user_name=b.name where a.name='服务台'";
		  List<Map<String,Object>> list2=jdbcTemplate.queryForList(sql1);
		  for(Map<String,Object> m:list2)
		  {
		    String tname=m.get("name").toString();
		    String fname=m.get("fullname").toString();
		    String sql3="insert into icd_major_member(id,incident_id,user_fullname,username)" +
		    		"values(uuid(),?,?,?)";
		    jdbcTemplate.update(sql3,id,fname,tname);
		  }
		  String sql4="insert into icd_major_member(id,incident_id,user_fullname,username)" +
          "values(uuid(),?,?,?)";
		  jdbcTemplate.update(sql4,id,model.getSupporterName(),model.getSupporterId());
		
		}

		mv.addObject("editable", editable);
		mv.addObject("currentUser", u);
		mv.addObject("model", model);
		return mv;

	}

	@RequestMapping("determineEdit")
	public ModelAndView determineEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView(
				"incident/incident/major/determineEdit");
		IcdIncident model = this.icdIncidentService.findOne(id);
		mv.addObject("model", model);

		if (StringUtils.isNotEmpty(model.getCusUserId())) {
			Map<String, Object> cusUser = this.appUserService
					.findOneDetailById(model.getCusUserId());

			mv.addObject("cusUser", cusUser);
		} else {
			mv.addObject("cusUser", new HashMap<String, Object>());
		}
		return mv;

	}

	@RequestMapping("incidentEdit")
	public ModelAndView incidentEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView(
				"incident/incident/major/incidentEdit");
		IcdIncident model = this.icdIncidentService.findOne(id);
		mv.addObject("model", model);
		return mv;

	}

	@RequestMapping("newIncidentEdit")
	public ModelAndView newIncidentEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView(
				"incident/incident/major/newIncidentEdit");
		IcdIncident model = new IcdIncident();
		model.setId(HibernateUUIDGenerator.generate());

		IUser user = ContextHolder.getLoginUser();

		mv.addObject("currentUser", user); 
		mv.addObject("model", model);

		return mv;

	}

	@RequestMapping("acceptEdit")
	public ModelAndView acceptEdit(String id, HttpServletRequest req) {

		ModelAndView mv = new ModelAndView("incident/incident/major/acceptEdit");

		IcdIncident model = this.icdIncidentService.findOne(id);

		Map<String, Object> cusUser = this.appUserService
				.findOneDetailById(model.getCusUserId());

		mv.addObject("cusUser", cusUser);

		mv.addObject("model", model);
		SrcServiceService srcServiceService = ContextHolder
				.getSpringBean("srcServiceService");

		if (model.getServiceCategoryId() != null) {
			SrcService srcService = srcServiceService.findOne(model
					.getServiceCategoryId());
			mv.addObject("srcServiceName", srcService.getName());
			int t1Remote_h = 1;
			int t1Remote_m = 1;

			int t2Remote_h = 1;
			int t2Remote_m = 1;
			mv.addObject("srcServiceRemoteTime", t1Remote_h + "时" + t1Remote_m
					+ "分");
			mv.addObject("srcServiceLocalTime", t2Remote_h + "时" + t2Remote_m
					+ "分");
		}

		return mv;
	}

	@RequestMapping("getSystemInfo")
	@ResponseBody
	public Map<String, Object> findBySystemInfo(String categoryId,
			HttpServletRequest req) {

		IcdCategoryService icdCategoryService = ContextHolder
				.getSpringBean("icdCategoryService");

		IcdCategory category = icdCategoryService.findOne(categoryId);

		int _2hourTotal = icdIncidentMajorService.get2HourTotal(categoryId);
		int _over2HourSolveTotal = icdIncidentMajorService
				.getOver2HourSolveTotal(categoryId);

		Map<String, Object> map = new java.util.HashMap<>();

		map.put("category", category);
		map.put("_2hourTotal", _2hourTotal);
		map.put("_over2HourSolveTotal", _over2HourSolveTotal);

		return map;
	}

	@RequestMapping("judgeEdit")
	@ResponseBody
	public ModelAndView judgeEdit(String id, HttpServletRequest req) {

		IcdIncidentController icdIncidentController = ContextHolder
				.getSpringBean("icdIncidentController");
		ModelAndView mv = icdIncidentController.view(id, req);

		mv.setViewName("incident/incident/major/judgeEdit");
		return mv;
	}

	@RequestMapping("judgeLevel1")
	@ResponseBody
	public ResultMessage judgeLevel1(String id, String suggestion,
			HttpServletRequest req) {

		IcdIncident model = this.icdIncidentService.findOne(id);

		if (true) {

			return ResultMessage.failure("当前事件已经是重要的事件！");
		} else {

			JdbcTemplate jdbcTemplate = ContextHolder
					.getSpringBean("jdbcTemplate");
			jdbcTemplate
					.update("UPDATE icd_incident SET status='重要事件处理',major_determine='担当已判定',priority_name='一级'  WHERE id='"
							+ id + "'");
			String activityId = "sid-F65009AA-8010-43E2-94BD-4D76E3A79897";
			bpmProcessRunService.jumpto(model.getProcessId(), activityId,
					ContextHolder.getLoginUsername(), suggestion);

			return ResultMessage.success();
		}
	}

	@RequestMapping("judgeMajor")
	@ResponseBody
	public ResultMessage judgeMajor(String id, String areMajor,
			String suggestion, HttpServletRequest req) {

		IcdIncident model = this.icdIncidentService.findOne(id);
		if (true && "是".equals(areMajor)) {
			return ResultMessage.failure("当前事件已经是重要的事件！");
		} else {
			JdbcTemplate jdbcTemplate = ContextHolder
					.getSpringBean("jdbcTemplate");
			if ("是".equals(areMajor)) {

				jdbcTemplate
						.update("UPDATE icd_incident SET  major_determine='"
								+ suggestion + "',are_major=1  WHERE id='" + id
								+ "'");
				itsm.isperp.module.service.incident.IcdIncidentMajorService icdIncidentMajorService = itsm.isperp.framework.core.context.ContextHolder
						.getSpringBean("icdIncidentMajorService");
				icdIncidentMajorService.initMember(id);
			} else {
				// 取消
				jdbcTemplate
						.update("UPDATE icd_incident SET   are_major=0  WHERE id='"
								+ id + "'");
			}

			return ResultMessage.success();
		}
	}

}
